package com.itheima.behavior.service.impl;

import com.itheima.behavior.service.CollectService;
import com.itheima.common.redis.CacheService;
import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.utils.thread.MpThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CacheService cacheService;

    private static final String USER_COLLECT_KEY = "user_collect:%s";
    private static final String COLLECT_COUNT_KEY = "collect_count";

    @Override
    public ResponseResult collectBook(Integer id) {
        return handleCollect("book", id.toString());
    }

    @Override
    public ResponseResult cancelCollectBook(Integer id) {
        return handleCancelCollect("book", id.toString());
    }

    @Override
    public ResponseResult collectNote(String id) {
        return handleCollect("note", id);
    }

    @Override
    public ResponseResult cancelCollectNote(String id) {
        return handleCancelCollect("note", id);
    }

    @Override
    public ResponseResult collectReview(String id) {
        return handleCollect("review", id);
    }

    @Override
    public ResponseResult cancelCollectReview(String id) {
        return handleCancelCollect("review", id);
    }

    /**
     * 统一处理收藏
     */
    private ResponseResult handleCollect(String type, String targetId) {
        collect(type, targetId);
        Map<String, Object> result = new HashMap<>();
        result.put("collected", true);
        result.put("count", getCollectCount(type, targetId));
        return ResponseResult.okResult(result);
    }

    /**
     * 统一处理取消收藏
     */
    private ResponseResult handleCancelCollect(String type, String targetId) {
        cancelCollect(type, targetId);
        Map<String, Object> result = new HashMap<>();
        result.put("collected", false);
        result.put("count", getCollectCount(type, targetId));
        return ResponseResult.okResult(result);
    }

    /**
     * 收藏核心方法
     */
    private void collect(String type, String targetId) {
        Integer userId = MpThreadLocalUtil.getUser().getId();
        String userKey = String.format(USER_COLLECT_KEY, userId);
        String targetKey = type + ":" + targetId;

        cacheService.hPut(userKey, targetKey, "1");
        cacheService.hIncrBy(COLLECT_COUNT_KEY, targetKey, 1);
    }

    /**
     * 取消收藏核心方法
     */
    private void cancelCollect(String type, String targetId) {
        Integer userId = MpThreadLocalUtil.getUser().getId();
        String userKey = String.format(USER_COLLECT_KEY, userId);
        String targetKey = type + ":" + targetId;

        cacheService.hDelete(userKey, targetKey);
        cacheService.hIncrBy(COLLECT_COUNT_KEY, targetKey, -1);
    }

    /**
     * 获取收藏数
     */
    private Long getCollectCount(String type, String targetId) {
        String targetKey = type + ":" + targetId;
        Object count = cacheService.hGet(COLLECT_COUNT_KEY, targetKey);
        return count != null ? Long.parseLong(count.toString()) : 0L;
    }

    /**
     * 是否收藏过
     */
    public boolean isCollected(String type, String targetId) {
        Integer userId = MpThreadLocalUtil.getUser().getId();
        String userKey = String.format(USER_COLLECT_KEY, userId);
        String targetKey = type + ":" + targetId;
        return cacheService.hExists(userKey, targetKey);
    }

    /**
     * 获取用户的收藏列表
     */
    @Override
    public ResponseResult getUserCollections() {
        Integer userId = MpThreadLocalUtil.getUser().getId();
        String userKey = String.format(USER_COLLECT_KEY, userId);
        Map<Object, Object> collections = cacheService.hGetAll(userKey);
        List<Map<String, String>> result = new ArrayList<>();
        if (collections != null && !collections.isEmpty()) {
            for (Object key : collections.keySet()) {
                String targetKey = key.toString();
                // targetKey格式: "book:123" 或 "note:abc" 或 "review:xyz"
                String[] parts = targetKey.split(":", 2);
                if (parts.length == 2) {
                    Map<String, String> item = new HashMap<>();
                    item.put("type", parts[0]);
                    item.put("id", parts[1]);
                    result.add(item);
                }
            }
        }
        return ResponseResult.okResult(result);
    }
}